Imports System
Imports Microsoft.VisualBasic

Imports System.Text
Imports System.IO.Ports
Imports System.Windows.Forms


Public Class ManagementConsole
    Private GPSInfo As New GPSSentenceHandler
    Protected Shared strActiveSerialPort As String
    Protected Shared strSourceFile As String
    Private LogFile As New Logging.FileLogTraceListener
    Private MyDashboardSettings As New DashboardSettings
    Private blnTimeToReadLine As Boolean = False
    Private Event TimeToReadLine()
    Private MyReader As Microsoft.VisualBasic.FileIO.TextFieldParser


    Public Sub New()

        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        Dim Quad As New frmAfbeeldenQuad
        Quad.Show()
        Dim Wind As New frmAfbeeldenWind
        Wind.Show()
        AddHandler GPSInfo.NewGroundSpeedInKnots, AddressOf Quad.QuadControl1.ProcessSpeedInKnots
        AddHandler GPSInfo.NewDepthInMeters, AddressOf Quad.QuadControl1.ProcessDepthInMeters
        AddHandler GPSInfo.NewWaterTemperature, AddressOf Quad.QuadControl1.ProcessWaterTemperature

        AddHandler GPSInfo.NewWindDirection, AddressOf Wind.WindControl1.ProcessWindAngle
        AddHandler GPSInfo.NewWindForceInKnots, AddressOf Wind.WindControl1.ProcessWindForce
        AddHandler GPSInfo.NewGroundSpeedInKnots, AddressOf Wind.WindControl1.ProcessBoatSpeed

        LogFile.BaseFileName = "c:\windows\temp\ManagementConsole.txt"

        Me.Timer1.Start()
    End Sub

    Public Shared Property SourceFile() As String
        Get
            SourceFile = strSourceFile
        End Get
        Set(ByVal value As String)
            strSourceFile = value
        End Set
    End Property

    Public Shared Property ActiveSerialPort() As String
        Get
            ActiveSerialPort = strActiveSerialPort
        End Get
        Set(ByVal value As String)
            strActiveSerialPort = value
        End Set
    End Property

    Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
        Dim ReceivedData As New System.Web.UI.WebControls.StringArrayConverter
        Try
            GPSInfo.ParseSerialData(ReceivedData.ConvertFromString(SerialPort1.ReadLine))
        Catch ex As Exception
            LogFile.WriteLine("ERROR while processing serial data: " & ex.Message)
        End Try
    End Sub

    Private Sub Preferences_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Preferences.Click
        Dim Bronkeuze As New DlgPreferences
        Try
            Bronkeuze.ShowDialog()
        Catch ex As Exception
            LogFile.WriteLine("ERROR while opening Preferences dialog: " & ex.Message)
        End Try

    End Sub

    Private Sub File_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles File.Click
        Me.StatusStrip1.Items("ComPort").Text = "Communication via: " & SourceFile

        If SourceFile = "" Then
            MsgBox("First choose an import file containing NMEA data. The Preferences dialog will now be opened.")
            Me.Preferences.PerformClick()
        Else
            LeesPerseconde()

            'Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(SourceFile)
            '    MyReader.TextFieldType = FileIO.FieldType.Delimited
            '    MyReader.SetDelimiters(",")
            '    Dim currentRow As String()
            '    While Not MyReader.EndOfData
            '        Try
            '            currentRow = MyReader.ReadFields()
            '            GPSInfo.ParseSerialData(currentRow)
            '        Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
            '            LogFile.WriteLine("ERROR: Line is invalid and will be skipped. " & ex.Message)
            '        End Try
            '    End While
            'End Using
        End If

    End Sub

    Private Sub OpenenToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenToolStripMenuItem.Click
        Me.StatusStrip1.Items("ComPort").Text = "Communicatie via: " & ActiveSerialPort

        If ActiveSerialPort = "" Then
            MsgBox("First choos a serial communication port for NMEA input. The Preferences dialog will now be opened.")
            Me.Preferences.PerformClick()
        End If
        Try
            With Me.SerialPort1
                .PortName = ActiveSerialPort
                .BaudRate = 19200
                .DataBits = 8
                .StopBits = StopBits.One
                .Parity = Parity.None
                .Open()
            End With
        Catch ex As Exception
            LogFile.WriteLine("ERROR opening serial port: " & ex.Message)
        End Try
    End Sub

    Private Sub CloseToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CloseToolStripMenuItem.Click
        If ActiveSerialPort = "" Then
            MsgBox("You can only close a serial port if you have an open serial port.")
        End If
        Try
            With Me.SerialPort1
                .Close()
                Me.StatusStrip1.Items("ComPort").Text = "Communication closed."
            End With
        Catch ex As Exception
            LogFile.WriteLine("ERROR closing the serial port: " & ex.Message)
        End Try

    End Sub

    Private Sub ManagementConsole_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        MyDashboardSettings.Reload()
        ActiveSerialPort = MyDashboardSettings.ComPort
        'Me.DataBindings.Add(New Binding(ActiveSerialPort, MyDashboardSettings, "Comport"))
    End Sub

    Private Sub ManagementConsole_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        My.Settings.Item("Comport") = ActiveSerialPort
        My.Settings.Save()
        MyDashboardSettings.ComPort = ActiveSerialPort
        MyDashboardSettings.Save()
    End Sub


    Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        RaiseEvent TimeToReadLine()
    End Sub

    Private Sub LeesPerseconde()
        MyReader = New Microsoft.VisualBasic.FileIO.TextFieldParser(SourceFile)
        MyReader.TextFieldType = FileIO.FieldType.Delimited
        MyReader.SetDelimiters(",")
        Dim currentRow As String()
        While Not MyReader.EndOfData
            Try
                '     AddHandler Timer1.Tick, AddressOf LeesRegel
                currentRow = MyReader.ReadFields()
                GPSInfo.ParseSerialData(currentRow)
            Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
                LogFile.WriteLine("ERROR: Line is invalid and will be skipped. " & ex.Message)
            End Try
        End While
        'End Using

    End Sub
    Private Sub LeesRegel(ByVal sender As Object, ByVal e As System.EventArgs)
        blnTimeToReadLine = Not blnTimeToReadLine
        Dim currentRow As String()
        blnTimeToReadLine = True
        If blnTimeToReadLine = True Then
            currentRow = MyReader.ReadFields()
            GPSInfo.ParseSerialData(currentRow)
            Return
        End If
    End Sub
End Class